package com.joy.web.common.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.joy.common.exception.JsonException;
import com.joy.common.model.ApiResponse;
import com.joy.common.model.vo.FileInfoVO;
import com.joy.conf.properties.FilePathProperties;
import com.joy.common.enums.Status;
import com.joy.web.base.controller.BaseController;
import com.joy.web.common.service.IFileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Optional;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author yjzhao
 * @since 2019-09-20
 */
@Slf4j
@Controller
@RequestMapping("/file")
public class FileInfoController extends BaseController {

    @Autowired
    FilePathProperties filePathProperties;

    @Resource
    IFileInfoService fileInfoService;

    @PostMapping(value = "/localFileUp", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ApiResponse localFileUp(@RequestPart("uploadFile") MultipartFile uploadFile,
                                   String sourceType) {
        log.info("init localFileUp");
        if (uploadFile.isEmpty()) {
            ApiResponse.ofStatus(Status.UPLOAD_ERROR, false);
        }

        if (StrUtil.isEmpty(sourceType)) {
            sourceType = "common";
        }

        try {
            Optional<FileInfoVO> fileVOOp = fileInfoService.localFileUp(uploadFile, sourceType);
            if (!fileVOOp.isPresent()) {
                return ApiResponse.ofStatus(Status.UPLOAD_ERROR, false);
            }
            return ApiResponse.ofStatus(Status.OK, fileVOOp.get(), true);
        } catch (Exception e) {
            log.info("/file/localFileUp MyException:");
            e.printStackTrace();
            throw new JsonException(Status.UPLOAD_ERROR, "上传文件错误");
        }
    }

    /**
     * @Description 下载文件
     * @param filePath
     * @param response
     * @return
     * @Author yjzhao
     * @Date 2019/9/24 8:44
     **/
    @RequestMapping(value = "/localDownload")
    @ResponseBody
    public void download(String filePath, HttpServletResponse response) throws UnsupportedEncodingException {
        // 如果文件名不为空，则进行下载
        if (StrUtil.isEmpty(filePath)) {
            return;
        }

        //文件全路径
        String fileAllPath = StrBuilder.create(filePathProperties.getDir())
                .append(StrUtil.SLASH)
                .append(filePath).toString();

        //设置文件路径
        File file = new File(fileAllPath);
        if (!file.exists()) {
            // 如果文件不存在
            return;
        }

        //获取文件名称
        String fileNm = FileUtil.getName(fileAllPath);

        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNm , "UTF-8"));


        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


}
